<?php
if ( !class_exists( 'WP_Widget_Custom_Recent_Posts' ) ) {

    class WP_Widget_Custom_Recent_Posts extends WP_Widget {

        function WP_Widget_Custom_Recent_Posts() {

            $widget_ops = array( 'classname' => 'widget_custom_recent_posts', 'description' => __( 'Displays list of posts with an array of options', 'crp' ) );
            $this->WP_Widget( 'sticky-posts', __( 'Custom Recent Posts', 'crp' ), $widget_ops );
            $this->alt_option_name = 'widget_custom_recent_posts';

            add_action( 'save_post', array( &$this, 'flush_widget_cache' ) );
            add_action( 'deleted_post', array( &$this, 'flush_widget_cache' ) );
            add_action( 'switch_theme', array( &$this, 'flush_widget_cache' ) );

            load_plugin_textdomain('crp', false, basename( dirname( __FILE__ ) ) . '/languages' );

        }

        function widget( $args, $instance ) {

            global $post;

            $cache = wp_cache_get( 'widget_custom_recent_posts', 'widget' );

            if ( !is_array( $cache ) )
                $cache = array();

            if ( isset( $cache[$args['widget_id']] ) ) {
                echo $cache[$args['widget_id']];
                return;
            }

            ob_start();
            extract( $args );

            $title = apply_filters( 'widget_title', $instance['title'] );

            $number = $instance['number'];
            if(is_single() && $instance['related_posts']){
                $cats_post = wp_get_post_categories($post->ID);
                if(count($cats_post)){
                    if($instance['cats'])
                        $instance['cats'] = array_merge($instance['cats'],$cats_post);
                    else {
                        $instance['cats'] = $cats_post;
                    }
                }

            }
            $cats = ($instance['cats'] ? explode(',', $instance['cats']) : '');
            $order = $instance['order'];
            $orderby = $instance['orderby'];
            $show_thumbnail = $instance['show_thumbnail'];
            $show_title = $instance['show_title'];
            $show_desc = $instance['show_desc'];

            echo $before_widget;
            if ( $title ) {
                echo $before_title.$title.$after_title;
            }

            $args = array(
                'showposts' => $number,
                'order' => $order,
                'orderby' => $orderby,
                'category__in' => $cats
            );
            //Excerpt more filter
            $new_excerpt_more = create_function('$more', 'return "...";');
            add_filter('excerpt_more', $new_excerpt_more);

            $r = new WP_Query( $args );
            $i = 0;
            if ( $r->have_posts() ) :
                ?>
                <?php if($instance['first_detail']):$r->the_post();?>
					<div class="first_detail">
						<div class="thumbnail-image">
							<a href="<?php the_permalink()?>">
								<?php if($instance['width'] && $instance['height']):?>
									<?php the_post_thumbnail(array($instance['width'] , $instance['height']));?>
								<?php else:?>
									<?php the_post_thumbnail();?>
								<?php endif?>
							</a>
						</div>
						<h2 class="post-title"><a href="<?php the_permalink() ?>" title="<?php echo esc_attr( get_the_title() ? get_the_title() : get_the_ID() ); ?>"><?php if ( get_the_title() ) the_title(); else the_ID(); ?></a></h2>
						<div class="entry-content">
							<?php if($instance['show_readmore']):?>
								<?php $moreText = ($instance['morebutton_text'] ? $instance['morebutton_text'] : __('Xem th&#234;m >>'))?>
								<?php the_excerpt(); ?>
								<a href="<?php the_permalink();?>" class="more-link"><?php echo $moreText;?></a>
							<?php else:?>
								<?php the_content()?>
							<?php endif;?>
						</div>
					</div>
                
					<?php if ( $r->have_posts() ):?>
					<div class="more_posts">
						<ul>
							<?php while ( $r->have_posts() ) : $r->the_post(); ?>
							<li>
								<a href="<?php the_permalink() ?>" title="<?php echo esc_attr( get_the_title() ? get_the_title() : get_the_ID() ); ?>"><?php if ( get_the_title() ) the_title(); else the_ID(); ?></a>
							</li>
							<?php endwhile; ?>
						</ul>
					</div>
					<?php endif;?>
				<?php else:?>
					<?php if ( $r->have_posts() ):?>
						<ul class="post_list">
							<?php while ( $r->have_posts() ) : $r->the_post(); ?>
							<li>
								<?php if($show_thumbnail):?>
									<div class="thumbnail-image">
										<a href="<?php the_permalink()?>">
											<?php if($instance['width'] && $instance['height']):?>
												<?php the_post_thumbnail(array($instance['width'] , $instance['height']));?>
											<?php else:?>
												<?php the_post_thumbnail();?>
											<?php endif?>
										</a>
									</div>
								<?php endif;?>
								<?php if($show_title):?>
									<h2 class="post-title"><a href="<?php the_permalink() ?>" title="<?php echo esc_attr( get_the_title() ? get_the_title() : get_the_ID() ); ?>"><?php if ( get_the_title() ) the_title(); else the_ID(); ?></a></h2>
								<?php endif;?>
								<?php if($show_desc):?>
									<div class="entry-content">
										<?php if($instance['show_readmore']):?>
											<?php $moreText = ($instance['morebutton_text'] ? $instance['morebutton_text'] : __('Read more...'))?>
											<?php the_excerpt(); ?>
											<a href="<?php the_permalink();?>" class="more-link"><?php echo $moreText;?></a>
										<?php else:?>
											<?php the_content()?>
										<?php endif;?>
									</div>
								<?php endif;?>
							</li>
							<?php endwhile; ?>
						</ul>
					<?php endif;?>
				<?php endif;?>	
                <?php
                // Reset the global $the_post as this query will have stomped on it
                wp_reset_postdata();

            else :

                echo __('No posts found.', 'crp');

            endif;

            echo $after_widget;

            if ($cache) {
                $cache[$args['widget_id']] = ob_get_flush();
            }
            wp_cache_set( 'widget_cusrom_recent_posts', $cache, 'widget' );
        }

        function update( $new_instance, $old_instance ) {
            $instance = $old_instance;

            $instance['title'] = strip_tags( $new_instance['title'] );
            $instance['number'] = strip_tags( $new_instance['number'] );
            $instance['width'] = strip_tags( $new_instance['width'] );
            $instance['height'] = strip_tags( $new_instance['height'] );
            $instance['cats'] = (isset( $new_instance['cats'] )) ? implode(',', (array) $new_instance['cats']) : '';
            $instance['show_readmore'] = isset( $new_instance['show_readmore']);
            $instance['show_thumbnail'] = isset( $new_instance['show_thumbnail']);
            $instance['show_title'] = isset( $new_instance['show_title']);
            $instance['show_desc'] = isset( $new_instance['show_desc']);
            $instance['order'] = $new_instance['order'];
            $instance['orderby'] = $new_instance['orderby'];
            $instance['show_morebutton'] = isset( $new_instance['show_morebutton'] );
            $instance['related_posts'] = isset( $new_instance['related_posts'] );
            $instance['first_detail'] = isset( $new_instance['first_detail'] );
            $instance['morebutton_text'] = strip_tags( $new_instance['morebutton_text'] );

            $this->flush_widget_cache();

            $alloptions = wp_cache_get( 'alloptions', 'options' );
            if ( isset( $alloptions['widget_custom_recent_posts'] ) )
                delete_option( 'widget_custom_recent_posts' );

            return $instance;

        }

        function flush_widget_cache() {

            wp_cache_delete( 'widget_cusrom_recent_posts', 'widget' );

        }

        function form( $instance ) {

            // Set default arguments
            $instance = wp_parse_args( (array) $instance, array(
                'title' => '',
                'number' => '5',
                'cats' => '',
                'order' => 'DESC',
                'orderby' => 'date',
                'morebutton_text' => __('View More Posts', 'crp'),
                'show_readmore' => false,
                'first_detail'  => true,
                'related_posts' => false
            ) );

            // Or use the instance
            $title  = strip_tags($instance['title']);

            $number = strip_tags($instance['number']);
            $width = strip_tags($instance['width']);
            $height = strip_tags($instance['height']);
            $cats = $instance['cats'];
            $order = $instance['order'];
            $orderby = $instance['orderby'];
            $show_readmore = $instance['show_readmore'];
            $show_thumbnail = $instance['show_thumbnail'];
            $show_title = $instance['show_title'];
            $show_desc = $instance['show_desc'];
            $related_posts = $instance['related_posts'];
            $first_detail = $instance['first_detail'];

            //Let's turn $types and $cats into an array
            $cats = explode(',', $cats);

            //Count number of post types for select box sizing
            $cpt_types = get_post_types( array( 'public' => true ), 'names' );
            foreach ($cpt_types as $cpt ) {
                $cpt_ar[] = $cpt;
            }
            $n = count($cpt_ar);
            if($n > 10) { $n = 10; }

            //Count number of categories for select box sizing
            $cat_list = get_categories( 'hide_empty=0' );
            foreach ($cat_list as $cat ) {
                $cat_ar[] = $cat;
            }
            $c = count($cat_ar);
            if($c > 10) { $c = 10; }

            ?>

            <p><label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title', 'crp' ); ?>:</label>
                <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo $title; ?>" /></p>

            <p><label for="<?php echo $this->get_field_id( 'number' ); ?>"><?php _e( 'Number of posts', 'crp' ); ?>:</label>
                <input id="<?php echo $this->get_field_id( 'number' ); ?>" name="<?php echo $this->get_field_name( 'number' ); ?>" type="text" value="<?php echo $number; ?>" size="2" /></p>

			<p><label for="<?php echo $this->get_field_id( 'width' ); ?>"><?php _e( 'Thumbnail width', 'crp' ); ?>:</label>
                <input id="<?php echo $this->get_field_id( 'width' ); ?>" name="<?php echo $this->get_field_name( 'width' ); ?>" type="text" value="<?php echo $width; ?>" size="2" /></p>	

			<p><label for="<?php echo $this->get_field_id( 'height' ); ?>"><?php _e( 'Thumbnail height', 'crp' ); ?>:</label>
                <input id="<?php echo $this->get_field_id( 'height' ); ?>" name="<?php echo $this->get_field_name( 'height' ); ?>" type="text" value="<?php echo $height; ?>" size="2" /></p>		
				
            <p>
                <label for="<?php echo $this->get_field_id('related_posts'); ?>">
                    <input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id('related_posts'); ?>" name="<?php echo $this->get_field_name('related_posts'); ?>"<?php checked( (bool) $related_posts, true ); ?> />
                    <?php _e( 'article contains the list of the current article', 'crp' ); ?>
                </label>
            </p>

            <p>
                <label for="<?php echo $this->get_field_id('first_detail'); ?>">
                    <input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id('first_detail'); ?>" name="<?php echo $this->get_field_name('first_detail'); ?>"<?php checked( (bool) $first_detail, true ); ?> />
                    <?php _e( 'Show thumbnail and description at first item', 'crp' ); ?>
                </label>
            </p>

            <p>
                <label for="<?php echo $this->get_field_id('show_readmore'); ?>">
                    <input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id('show_readmore'); ?>" name="<?php echo $this->get_field_name('show_readmore'); ?>"<?php checked( (bool) $show_readmore, true ); ?> />
                    <?php _e( 'Show read more link', 'crp' ); ?>
                </label>
            </p>
			
			<p>
                <label for="<?php echo $this->get_field_id('show_thumbnail'); ?>">
                    <input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id('show_thumbnail'); ?>" name="<?php echo $this->get_field_name('show_thumbnail'); ?>"<?php checked( (bool) $show_thumbnail, true ); ?> />
                    <?php _e( 'Show thumbnail', 'crp' ); ?>
                </label>
            </p>
			
			<p>
                <label for="<?php echo $this->get_field_id('show_title'); ?>">
                    <input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id('show_title'); ?>" name="<?php echo $this->get_field_name('show_title'); ?>"<?php checked( (bool) $show_title, true ); ?> />
                    <?php _e( 'Show title', 'crp' ); ?>
                </label>
            </p>
			
			<p>
                <label for="<?php echo $this->get_field_id('show_desc'); ?>">
                    <input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id('show_desc'); ?>" name="<?php echo $this->get_field_name('show_desc'); ?>"<?php checked( (bool) $show_desc, true ); ?> />
                    <?php _e( 'Show description', 'crp' ); ?>
                </label>
            </p>

            <p>
                <label for="<?php echo $this->get_field_id('morebutton_text'); ?>"><?php _e( 'More button text', 'crp' ); ?>:</label>
                <input class="widefat" type="text" id="<?php echo $this->get_field_id('morebutton_text'); ?>" name="<?php echo $this->get_field_name('morebutton_text'); ?>" value="<?php echo $morebutton_text; ?>" />
            </p>

            <p>
                <label for="<?php echo $this->get_field_id('cats'); ?>"><?php _e( 'Select categories', 'crp' ); ?>:</label>
                <select name="<?php echo $this->get_field_name('cats'); ?>[]" id="<?php echo $this->get_field_id('cats'); ?>" class="widefat" style="height: auto;" size="<?php echo $c ?>" multiple>
                    <?php
                    $categories = get_categories( 'hide_empty=0' );
                    foreach ($categories as $category ) { ?>
                        <option value="<?php echo $category->term_id; ?>" <?php if( in_array($category->term_id, $cats)) { echo 'selected="selected"'; } ?>><?php echo $category->cat_name;?></option>
                    <?php }	?>
                </select>
            </p>

            <p>
                <label for="<?php echo $this->get_field_id('orderby'); ?>"><?php _e( 'Order by', 'upw' ); ?>:</label>
                <select name="<?php echo $this->get_field_name('orderby'); ?>" id="<?php echo $this->get_field_id('orderby'); ?>" class="widefat">
                    <option value="date"<?php if( $orderby == 'date') echo ' selected'; ?>><?php _e('Published Date', 'upw'); ?></option>
                    <option value="title"<?php if( $orderby == 'title') echo ' selected'; ?>><?php _e('Title', 'upw'); ?></option>
                    <option value="comment_count"<?php if( $orderby == 'comment_count') echo ' selected'; ?>><?php _e('Comment Count', 'upw'); ?></option>
                    <option value="rand"<?php if( $orderby == 'rand') echo ' selected'; ?>><?php _e('Random'); ?></option>
                </select>
            </p>

            <p>
                <label for="<?php echo $this->get_field_id('order'); ?>"><?php _e( 'Order', 'upw' ); ?>:</label>
                <select name="<?php echo $this->get_field_name('order'); ?>" id="<?php echo $this->get_field_id('order'); ?>" class="widefat">
                    <option value="DESC"<?php if( $order == 'DESC') echo ' selected'; ?>><?php _e('Descending', 'upw'); ?></option>
                    <option value="ASC"<?php if( $order == 'ASC') echo ' selected'; ?>><?php _e('Ascending', 'upw'); ?></option>
                </select>
            </p>

            <?php

        }

    }

    function init_WP_Widget_Custom_Recent_Posts() {

        register_widget( 'WP_Widget_Custom_Recent_Posts' );

    }

    add_action( 'widgets_init', 'init_WP_Widget_Custom_Recent_Posts' );

}
